<?php	//cart
function addtocart($id) {
    if (count($this->Session->read("cart")) > 0) {
        if (array_key_exists($id, $this->Session->read("cart"))) {
            $soluong = checkKhoHang($id);
            if ($this->Session->read("cart")[$id] < $soluong) {
                $this->Session->read("cart")[$id]++;
            } else {
                echo "<script>alert('Xin loi kho hang chung toi khong du!')</script>";
            }
        } else {
            $this->Session->read("cart")[$id] = 1;
        }
    }else{
        $this->Session->read("cart")[$id] = 1;
    }
	//echo($_SESSION["tongsanpham"] = layTongSanPhamTrongGioHang($this->Session->read("cart")));
	//echo($_SESSION["tongtien"] = layTongGiaSanPhamTrongGioHang($this->Session->read("cart")));
}

function layTongSanPhamTrongGioHang($array_cart) {
    $total = 0;
    if(is_array($array_cart)){
        foreach ($array_cart as $id => $qty) {
            $total+=$qty;
        }
    }
    return $total;
}

function layTongGiaSanPhamTrongGioHang($array_cart) {
    $total = 0;
    if(is_array($array_cart)){
        foreach ($array_cart as $id => $qty) {
            $price = layGiaTungSanPham($id);
            $total+=$price * $qty;
        }
    }
    return $total;
}

function layGiaTungSanPham($id) {
   $this->Product->id = $id;
   $this->set('priceProduct',$this->Product->read());
    $price = $priceProduct['Product']['price'];
    return $price;
}

function checkKhoHang($id) {
	$this->set('slProduct',$this->Product->read());
    $sl = $slproduct['Product']['quantity'];
    return $sl;
}

function updateCart() {
    foreach ($this->Session->read("cart") as $id => $qty) {
        if ($_POST[$id] <= 0) {
            unset($this->Session->read("cart")[$id]);
        } else {
            $soluong = checkKhoHang($id);
            if ($_POST[$id] < $soluong) {
                $this->Session->read("cart")[$id] = $_POST[$id];
            }else {
                echo "<script>alert('Xin loi kho hang chung toi khong du!')</script>";
            }
        }
    }
	$_SESSION["tongsanpham"] = layTongSanPhamTrongGioHang($this->Session->read("cart"));
    $_SESSION["tongtien"] = layTongGiaSanPhamTrongGioHang($this->Session->read("cart"));
}

function deleteItemCart($id) {
    unset($this->Session->read("cart")[$id]);
}

function deleteCart() {
    unset($this->Session->read("cart"));
}
?>